package com.zy.garbage.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

/**
 * jwt工具类
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "jwt.config")
public class JwtUtil {

    /**
     * 设置token
     * id:登录用户id
     * subject：登录用户名
     */
    private String secretString ;
    private long ttl;

    public String createJwt(String id, Map<String,String> map) {
//        设置失效时间
        long now = System.currentTimeMillis();//当前毫秒
        SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
        long exp = now + ttl;
//        创建jwtBuilder
        JwtBuilder builder = Jwts.builder().setId(id)
//                .setSubject(name)
                .setIssuedAt(new Date())
                .signWith(key, SignatureAlgorithm.HS256);

//        数据map设置claims
        for(Map.Entry<String,String> entry :map.entrySet()){
            builder.claim(entry.getKey(),entry.getValue());
        }

//       设置过期时间， 创建token
        builder.setExpiration(new Date(exp));
        String token = builder.compact();

        return token;
    }

    /**
     * 解析token
     * id:登录用户id
     * subject：登录用户名
     */
    public Claims parseJwt(String token){
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(secretString)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}
